/**
 * Created by zyh on 2019/4/12.
 */

const isDebug = false; // true测试版本  false正式版本

function getDomain() {
  // domain url
  var localdomain = 'http://cw.jnaw.top/mocks/dingding';
  var servedomain = 'http://mlhjl.jnaw.top/hjl';
  var domain = '';
  if (isDebug) {
    domain = localdomain;
  } else {
    domain = servedomain;
  }
  return domain;
}

// 有赞超市的地址
function getYouZanUrl() {
  var url = 'https://h5.youzan.com/wscshop/feature/K4nilHwZwW?common/url/create=&feature/K4nilHwZwW=&scan=3&from=kdt&sls=3wU9Ec';
  return url;
}

// jquery ajax
function ajax($, url, method, data, fun) {
  if (!method) {
    method = 'GET';
  }
  $.ajax({
    url: url,
    method: method,
    xhrFields: {
      withCredentials: true
    },
    data: data,
    success: function (res) {
      fun(res);
    }
  });
}

// axios
function axiosAjax(url, method, data, fun) {
  if (!method) {
    method = 'POST';
  }
  axios({
    url: url,
    method: method,
    xhrFields: {
      withCredentials: true
    },
    data: data,
    responseType: 'json', // 默认的
    withCredentials: true,
  }).then(function (response) {
    var res = response.data;
    if (fun) {
      fun(res);
    }
  }).catch(function (error) {
    if (fun) {
      fun(error);
    }
  })
}

function showToast(_this, str, times = 6) {
  if (!str) {
    return false;
  }
  _this.$Message.destroy();
  _this.$Message.error({
    content: str,
    duration: times
  });

}

/* json字符串转为json对象 */
function _toJson(str) {
  var res = '';
  if (str != '' && str != undefined && str != null) {
    if (typeof str == 'string') {
      str = str.trim();
      res = JSON.parse(str) ? JSON.parse(str) : eval('(' + str + ')');
    } else if (typeof str == 'object') {
      res = str;
    }
  }
  return res;
};

/* json对象转为json字符串 */
function _toStr(obj) {
  var res = '';
  if (typeof obj == 'string') {
    res = obj;
  } else if (typeof obj == 'object') {
    res = JSON.stringify(obj);
  }
  return res;
}

function idInArray(id, arr) {
  var len = arr.length
  var total = 0
  for (var i = 0; i < len; i++) {
    if (arr[i].id == id) {
      total = parseInt(total) + 1
      break
    }
  }
  return (parseInt(total) > 0) ? true : false
}
/**
 * 对象转换成url地址
 * @param obj
 * @param url
 * @returns {*}
 */
function _obj_to_url(obj, url) {
  var str = "";
  for (var key in obj) {
    if (str != "") {
      str += "&";
    }
    str += key + "=" + obj[key];
  }
  if (typeof url != 'undefined') {
    return url.indexOf('?') >= 0 ? url + '&' + str : url + '?' + str;
  } else {
    return str;
  }
};


//取某一字符串的最后一个字符并返回该字符
function getLastLen(str, len) {
  // return str.substring(str.length - 1, str.length);
  return str.substr(str.length - parseInt(len), str.length);
};

//删除数组下标为i的数组元素，并返回剩余的数组
function removeArr(arr, dx) {
  if (isNaN(dx) || dx > arr.length) {
    return false;
  }
  var arr_l = [];
  for (var i = 0; i < arr.length; i++) {
    if (i < dx) {
      arr_l[i] = arr[i];
    } else if (i > dx) {
      arr_l[i - 1] = arr[i];
    }
  }
  return arr_l;
};

//添加多项元素并返回新数组
function addArr(arr, ind, newArr) {
  for (var i = 0; i < newArr.length; i++) {
    arr.splice(parseInt(ind + i), 0, newArr[i]);
  }
  return arr;
}

// 删除数组中为空的数值并返回剩余数组
function removeNullArr(arr) {
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] != '') {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

// session 存储
function sessionSet(key, val) {
  sessionStorage.setItem(key, val);
}
function sessionGet(key) {
  return sessionStorage.getItem(key);
}
function sessionRem(key) {
  sessionStorage.removeItem(key);
}
function sessionClear() {
  sessionStorage.clear();
}

// localStorage 存储
function localStorageSet(key, val) {
  localStorage.setItem(key, val);
}
function localStorageGet(key) {
  return localStorage.getItem(key);
}
function localStorageRem(key) {
  localStorage.removeItem(key);
}
function localStorageClear() {
  localStorage.clear();
}

// 将小数转换为百分比
function toPercent(numb) {
  numb = (numb).toFixed(4);
  var numbStr = JSON.stringify(numb);
  // console.log(numbStr);
  var numbArr = numbStr.split('.');
  if (numbArr.length > 1) {
    var len = numbArr[1].length;
    // Math.pow(10,len) 10的len次方
    return (Math.round(numb * Math.pow(10, len)) / Math.pow(10, len - 2)).toFixed(2) + '%';
  } else {
    return (numb * 100) + '%';
  }
}

//四舍五入保留2位小数（不够位数，则用0替补）
function keepTwoDecimalFull(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    console.log('传递参数错误，请检查！');
    return num;
  }
  result = Math.round(num * 100) / 100;
  var s_x = result.toString();
  var pos_decimal = s_x.indexOf('.');
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
  }
  //return s_x;

  //转化为每3个一个逗号的金钱格式
  var s_xArr = s_x.split('.');
  var integer = s_xArr[0];
  var decimals = s_xArr[1];

  var integer = toMoney(integer);
  return integer + '.' + decimals;
}

//转化为每3个一个逗号的金钱格式
function toMoney(str) {
  var len = str.length,
      lastIndex,
      arr = [];
  while (len > 0) {
    lastIndex = len;
    len -= 3;
    arr.unshift(str.substring(len, lastIndex));
  }
  return arr.join(',');
};

// 设置数字几位数显示；例console.log(fix(5, 2));输出结果为05
function fix(num, length) {
  return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
}

//时间差计算
function getTimeDifference(timeSet) {//timeSet开始时间格式为2016-10-10 09:56:47
  var bng = timeSet;
  var end = new Date();
  endyear = fix(end.getFullYear(), 4);
  endmonth = fix(parseInt(end.getMonth() + 1), 2);
  endday = fix(end.getDate(), 2);
  endhours = fix(end.getHours(), 2);
  endminutes = fix(end.getMinutes(), 2);
  endseconds = fix(end.getSeconds(), 2);
  end = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':' + endminutes + ':' + endseconds;
  var bngDate = new Date(bng.substr(0, 4), bng.substr(5, 2) - 1, bng.substr(8, 2), bng.substr(11, 2), bng.substr(14, 2), bng.substr(17, 2));
  var endDate = new Date(end.substr(0, 4), end.substr(5, 2) - 1, end.substr(8, 2), end.substr(11, 2), end.substr(14, 2), end.substr(17, 2));

  var dateDifference = endDate.getTime() - bngDate.getTime();//时间差的毫秒数
  var days = Math.floor(dateDifference / (24 * 3600 * 1000))//计算出相差天数
  //计算出小时数
  var leave1 = dateDifference % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000));
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000));
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000);
  // console.log(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒");
  var retDate = days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";
  if (days != 0) {
    retDate = days + '天前'
  } else {
    if (hours != 0) {
      retDate = hours + '小时前'
    } else {
      if (minutes != 0) {
        retDate = minutes + '分钟前'
      } else {
        retDate = seconds + '秒前'
      }
    }
  }
  return retDate;
}

//字符串 超出长度显示···
/*
 str : 内容
 length : 最大长度
 */
function String_out_of_range(str, Maxleng) {

  var length = str.length;
  Maxleng = parseInt(Maxleng);
  if (length > Maxleng) {
    str = str.substring(0, Maxleng) + ' ··· ';
  }
  return str;
}

/*用途：检查输入的Email信箱格式是否正确;输入：strEmail：字符串返回：如果通过验证返回true,否则返回false*/
function checkEmail(strEmail) {
  var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
  if (emailReg.test(strEmail)) {
    return true;
  } else {//warnAlter("您输入的Email地址格式不正确！");
    return false;
  }
}

/*用途：检查输入手机号码是否正确输入：s：字符串;返回：如果通过验证返回true,否则返回false*/
function checkMobile(phone) {
  //正则：验证电话号码手机号码，包含至今所有号段
  var reg = /^(1[3|4|5|6|7|8|9])[\d]{9}$/;
  if (!reg.test(phone)) {//alert("电话号码格式错误!");obj.value="";obj.focus();
    return false;
  }
  else {//alert("您的电话号码:"+phone);
    return true;
  }
}

//获取url的参数
function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null)return unescape(r[2]);
  return null;
}